//
//  AppDelegate+AMap.m
//  Runner
//
//  Created by 学大教育 on 2023/10/23.
//

#import "AppDelegate+AMap.h"
static const NSString* _CHANNEL_METHOD_LOCATION = @"amap_flutter_location";
static const NSString* _FLU_AMAP_METHOD_STARTLOCATION = @"startLocation";

@implementation AppDelegate (AMap)


-(AMapLocationManager *)localManager{
    AMapLocationManager *_localManager = objc_getAssociatedObject(self, _cmd);
    
    //设置期望定位精度
    [_localManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [_localManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [_localManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    [_localManager setLocationTimeout:10];
    
    //设置逆地理超时时间
    [_localManager setReGeocodeTimeout:5];

    _localManager.delegate = self;
    return _localManager;
}
 
-(void)setLocalManager:(AMapLocationManager *)localManager{
    objc_setAssociatedObject(self, @selector(localManager), localManager, OBJC_ASSOCIATION_RETAIN);
    //objc_setAssociatedObject(self, &kAssociatedNewName, newName, OBJC_ASSOCIATION_RETAIN);
    
}
#pragma mark - AMapLocationManagerDelegate -
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager*)locationManager
{
    [locationManager requestAlwaysAuthorization];
}
- (void)AMapMethodChannelWithController:(FlutterViewController *)controller;
{
    NSMutableDictionary *methodsDic = [NSMutableDictionary dictionary];
    [methodsDic setValue:@"startLocation:" forKey:_FLU_AMAP_METHOD_STARTLOCATION];
    
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                             methodChannelWithName:_CHANNEL_METHOD_LOCATION
                                             binaryMessenger:controller.binaryMessenger];
    WeakSelf(self);
    [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
       // This method is invoked on the UI thread.
       // TODO
  
        StrongSelf(self);
        NSString *selStr = methodsDic[call.method];
        SEL sel = NSSelectorFromString(selStr);
        [self performSelectorWithArgs:sel,call.arguments];
     }];
}

//开始定位
- (void)startLocation:(NSDictionary *)arg
{
    self.localManager = [[AMapLocationManager alloc]init];
    [[self localManager] requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {

               if (error)
               {
                   NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);

                   if (error.code == AMapLocationErrorLocateFailed)
                   {
                       NSLog(@"定位失败");
                       return;
                   }
               }

               NSLog(@"location:%@", location);

               if (regeocode)
               {
                   NSLog(@"reGeocode:%@", regeocode);
               
               }
        }];
}
@end
